import os
import sys
import time

import pymysql


def save_stat_to_db(_project, date):
    _filename = 'D:/gitstat/' + _project + '-' + date + '.txt'

    print(_filename)
    rows = []
    with open(_filename, encoding='UTF-8') as file_obj:
        data = file_obj.readlines()
        print(data)
        addnum = 0
        subnum = 0
        author = ''
        for line in data:
            aa = line.find('\t')
            if aa > -1:
                value1 = line[0:aa]
                addnum += 0 if value1 == '-' else int(value1)
                substr = line[aa + 1:len(line)]
                value2 = substr[0:substr.find('\t')]
                subnum += 0 if value2 == '-' else int(value2)
            bb = line.find('author:')
            if bb > -1:
                name = line[7:len(line) - 1]
                if author == '':
                    author = name
                elif author != name:
                    add_row(addnum, author, rows, subnum)
                    addnum = 0
                    subnum = 0
                    author = name
        if author != '':
            add_row(addnum, name, rows, subnum)

    print(rows)

    # 1.连接
    conn = pymysql.connect(host='10.133.5.59', port=3306, user='root', password='1986z11z20Z!', db='vrrhelp',
                           charset='utf8')
    # conn.select_db('vrrhelp')
    # 2.创建游标
    cur = conn.cursor()

    sql1 = 'delete from gitstat where date = %s and project = %s'
    effect_row = cur.execute(sql1, (date, _project))  # effect_row=1

    for row in rows:
        sql2 = 'insert into gitstat(date,author,addnum,subnum,totalnum,project) values(%s,%s,%s,%s,%s,%s)'
        effect_row = cur.execute(sql2, (
            date, row['name'], row['addnum'], row['subnum'], row['addnum'] - row['subnum'], _project))  # effect_row=1

    # 一定记得commit
    conn.commit()
    # 4.关闭游标
    cur.close()
    # 5.关闭连接
    conn.close()


def add_row(addnum, name, rows, subnum):
    check = True
    for row in rows:
        if row['name'] == name:
            newrow = {'name': name, 'addnum': row['addnum'] + addnum, 'subnum': row['subnum'] + subnum}
            rows.remove(row)
            rows.append(newrow)
            check = False
            break
    if check:
        rows.append({'name': name, 'addnum': addnum, 'subnum': subnum})


if __name__ == '__main__':
    save_stat_to_db('saf-acm-iam-be', '2022-03-26')
